<?php
/**
 * [woniu] Copyright (c) 2016/8/18
 * join.ctrl
 * 报名入口控制器
 */
defined('IN_IA') or exit('Access Denied');
if (empty($_W['fans']['nickname'])){
	$_W['fans'] = getInfo();
}
$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$pagetitle = '报名信息填写';
$activityid        = intval($_GPC['activityid']);
$activity          = model_activity::getSingleActivity($activityid, '*');
if ($_W['container']!='wechat'){
	fx_message('请用微信打开此连接报名', '', 'error', '点击返回');
}
if ($activity['show']==0 || $activity['review']!=1){
	fx_message('当前活动没有开放报名', '', 'error', '点击返回');
}
if ($_W['_config']['guanzhu_join']==2 && empty($_W['fans']['follow'])){
	fx_message('您还未关注,不能报名', app_url('activity/detail/display', array ('activityid' => $activityid)), 'warning');
}
$blacklist = pdo_get('fx_member_blacklist', array('uid' => $_W['member']['uid']), array('uid'));
if ($blacklist['uid']){
	fx_message('对不起您被主办方屏蔽了', app_url('activity/detail/display', array ('activityid' => $activityid)), 'error','请联系主办方解封');
}

$optionid          = intval($_GPC['optionid'])?intval($_GPC['optionid']):0;
$teamnum           = intval($_GPC['teamnum']) ? intval($_GPC['teamnum']) : 1;
$activity['prize'] = unserialize($activity['prize']);//积分
$form              = unserialize($activity['form']);//系统表单

if (!is_array($form['realname'])){//表单优化，数据兼容
	$sysform['realname']['title'] = $form['realname'];
	$sysform['realname']['need'] = 1;
	$sysform['realname']['show'] = $form['realnameshow'];
	
	$sysform['mobile']['title'] = $form['mobile'];
	$sysform['mobile']['need'] = 1;
	$sysform['mobile']['show'] = $form['mobileshow'];
	
	$sysform['gender']['title'] = $form['gender'];
	$sysform['gender']['need'] = $form['gendermust'];
	$sysform['gender']['show'] = $form['gendershow'];
	
	$sysform['birthyear']['title'] = $form['birthyear'];
	$sysform['birthyear']['need'] = $form['birthmust'];
	$sysform['birthyear']['show'] = $form['birthshow'];
	
	$sysform['resideprovince']['title'] = $form['resideprovince'];
	$sysform['resideprovince']['need'] = $form['residemust'];
	$sysform['resideprovince']['show'] = $form['resideshow'];
}else{
	$sysform = $form;
	$sysform['realname']['show'] = $form['realname']['show']=='' || $form['realname']['show']?1:0;
	$sysform['mobile']['show'] = $form['mobile']['show']=='' || $form['mobile']['show']?1:0;
	if (count($sysform)>2){
		$sysform['gender']['show'] = $form['gender']['show']=='' || $form['gender']['show']?1:0;
		$sysform['birthyear']['show'] = $form['birthyear']['show']=='' || $form['birthyear']['show']?1:0;
		$sysform['resideprovince']['show'] = $form['resideprovince']['show']=='' || $form['resideprovince']['show']?1:0;
	}
}
//验证名额，每次进入加载剩余名额数量、及规格
$condition = " activityid = $activityid and status <> 5 and (status <> 0 or paytype = 'delivery')";
$quota = $activity['quota'];
if ($activity['hasoption']){//规格选项
	$option = model_activity::getSingleActivityOption($optionid);
	$activity['aprice'] = $option['aprice'];
	$activity['falsenum'] = $option['falsenum'] ? $option['falsenum'] : 0;
	$quota = $option['quota'];
}
$joinnum = model_records::getJoinNum($activityid, $optionid) + $activity['falsenum'];

if($op =='display'){
	load()->model('mc');
	$dc = $_GPC['dc'] == 'yes'?TRUE:FALSE; //是否积分抵扣
	$pay_price = sprintf("%.2f", $activity['aprice'] * $teamnum);
	$profile   = mc_fetch($_W['member']['uid']);//读取会员信息
	if(empty($profile['email']) || (!empty($profile['email']) && substr($profile['email'], -6) == 'we7.cc' && strlen($profile['email']) == 39)) {
		$profile['email'] = '';
	}
	$activityForm = model_activity::getNumActivityForm($activityid,'app');//读取表单
	$marketing    = model_activity::getMarketing($activityid);//优惠
	$afterMarketing = model_records::getafterMarketing($pay_price, $teamnum, $activity['id'], $dc); //获取优惠后的价格等参数
	if(!$optionid && $activity['hasoption']){
		fx_message ('请选择活动类型', app_url('activity/detail/display', array ('activityid' => $activityid)), 'warning');
	}
	if($joinnum >= $quota && $quota>0) {
		fx_message ('很遗憾！名额已经满了', app_url('activity/detail/display', array ('activityid' => $activityid)), 'warning');
	}
	if ($_W['openid'] == 'o7CHdvlvTW37Kg51Hmycd0y9EmUk'){
		include $this->template ('join_1');
	}else{
		include $this->template ('join');	
	}
	exit;
}

if($_W['ispost'] && $op == 'join') {
	setcookie("sms_code", '');
	$data_member = $_GPC['member'];
	if (empty($data_member['realname']) && $systemform['realnameshow']) {
		fx_message ('请输入姓名','history.go(-1)','warning');
	}
	if (empty($data_member['mobile']) && $systemform['mobileshow']) {
		fx_message ('请输入手机','history.go(-1)','warning');
	}
	//$_W['openid'] == 'o7CHdvlvTW37Kg51Hmycd0y9EmUk'? exit:'';
	$data = array (
			'uid' => $_W['member']['uid'],
			'activityid' => $activityid,
			'uniacid' => $_W['uniacid'],
			'openid' => $_W['fans']['openid'],
			'teamnum' => $teamnum,
			'nickname' => $_W['fans']['nickname'],
			'headimgurl' => $_W['fans']['avatar'],
			'orderno' => createUniontid(),
			'realname' => $data_member['realname'],
			'mobile' => $data_member['mobile'],
			'gender' => $_GPC['gender']==0 ? '保密' : ($_GPC['gender']==1?'男':'女'),
			'pic' => $_GPC['pic'],
			'msg' => htmlspecialchars_decode($_GPC['msg']),
			'optionid' => $optionid?$optionid:0,
			'optionname' => $option['title'],
			'review' => $activity['hasreview']?0:1,
			'status' => 2,
			'merchantid' => $activity['merchantid']?$activity['merchantid']:0
	);
	
	if ($activity['aprice'] > 0){//获取付费金额
		$data['aprice'] = $_GPC['aprice'];
		$data['price'] = $_GPC['price'];
		$data['status'] = 0;
	}
	$condition = "activityid = $activityid and status <> 5 and openid='{$_W['openid']}'";
	$findUser = pdo_fetch("SELECT id FROM " . tablename ('fx_activity_records') . " WHERE $condition");
	if(!empty($findUser) && !$activity['hasjoin']){
		fx_message ('不能重复报名！', $this->createMobileUrl ('activity/detail/display', array ('activityid' => $activityid)), 'warning');
	}else{
		if ($quota>0){
			$joinnum = model_records::getJoinNum($activityid, $optionid) + $activity['falsenum'];
			if($joinnum >= $quota) {
				fx_message ('很遗憾！名额已经满了', app_url('activity/detail/display', array ('activityid' => $activityid)), 'warning');
			}elseif($joinnum + $teamnum > $quota){
				fx_message ("当前活动仅剩 " . ($quota - $joinnum) . ' 个名额，点击确定重新填写', '' , 'warning');
			}
		}
		$result = pdo_insert('fx_activity_records', $data);
		if (!empty($result)){
			$recordid = pdo_insertid();
			//保存自定义表单信息
			$form_ids = $_GPC['form_id'];
			$len = count($form_ids);
			$form_items = array();
			for ($k = 0; $k < $len; $k++) {
				$form_items[$k] = is_array($_GPC["form_item_val_".$k]) ? implode(',',$_GPC["form_item_val_".$k]) : $_GPC["form_item_val_".$k];
				$form_id = $form_ids[$k];
				$a = array(
					"activityid" => $activityid,
					"recordid" => $recordid,
					"formid" => $form_id,
					"data" => $form_items[$k]
				);
				//表单数据
				pdo_insert("fx_form_data", $a);
			}
			//同步会员信息
			if (!empty($_GPC['gender']))
			{
				$data_member['gender'] = $_GPC['gender'];
			}
			if (!empty($_GPC['birth']))
			{
				$data_member['birthyear'] = $_GPC['birth']['year'];
				$data_member['birthmonth'] = $_GPC['birth']['month'];
				$data_member['birthday'] = $_GPC['birth']['day'];
			}
			if (!empty($_GPC['reside']))
			{
				$data_member['resideprovince'] = $_GPC['reside']['province'];
				$data_member['residecity'] = $_GPC['reside']['city'];
				$data_member['residedist'] = $_GPC['reside']['district'];
			}
			if ($_GPC['education']!='') $data_member['education'] = $_GPC['education'];
			if ($_GPC['constellation']!='') $data_member['constellation'] = $_GPC['constellation'];
			if ($_GPC['zodiac']!='') $data_member['zodiac'] = $_GPC['zodiac'];
			if ($_GPC['bloodtype']!='') $data_member['bloodtype'] = $_GPC['bloodtype'];
			
			if (!empty($data_member)){
				mc_update($_W['member']['uid'],$data_member);
			}
			//积分奖励
			if ($_W['_config']['creditstatus'] == 1 && $activity['prize']['credit'] > 0){
				fx_load()->model('credit');
				$credit_result = credit_update_credit1($_W['member']['uid'],$activity['prize']['credit'],1,"报名获取".$activity['prize']['credit'].'积分',2);
				$prizedata = $credit_result ? '系统奖励您<font color=" color="#FF7B33">'.$activity['prize']['credit'].'</font>积分':0;
			}
			if ($activity['aprice'] > 0){//判断是否为付费活动
				header("location:".app_url('pay/paytype/display', array('recordid' => $recordid)));
			}else{
				//生成核销码、二维码
				//$listNum = pdo_fetchall("SELECT hexiaoma as num FROM " . tablename ('fx_activity_records') . " WHERE activityid = $activityid");
				//$ma['hexiaoma'] = createNumber($listNum);
				$ma['hexiaoma'] = $data['hexiaoma'] = createRandomNumber(8);
				pdo_update('fx_activity_records', $ma, array('id' => $recordid, 'uniacid' => $_W['uniacid']));
				createQrcode::creategroupQrcode($data['orderno']);
				
				//报名成功通知
				message::join_success($_W['openid'], $activity, $recordid, app_url('records/records/list'));
				if($activity['smsswitch']){//发送短信
					$smsparams=array(
						'product' => $_W['_config']['sname'],
						'item'    => $activity['title'],
						'name'    => $data['realname'],
						'timestr' => date('m月d日 H:i',strtotime($activity['starttime'])),
						'idcode'  => $data['hexiaoma']
					);
					sendSMS($data['mobile'],$smsparams,$activity['smsnotify'],$_W['_config']['sms_type']);
				}
				if ($_W['_config']['admin_notice']){//管理员通知
					if ($activity['merchantid'])
					$merchant = model_merchant::getSingleMerchant($activity['merchantid'], '*');//读取主办方
					$openids = unserialize($activity['openids']);
					$openids = !empty($openids) ? $openids : unserialize($merchant['messageopenid']);
					$openids = !empty($openids) ? $openids : $_W['_config']['openids'];
					if (!empty($openids)){
						foreach($openids as $key=> $value){
							message::admin_notice($value, $activity, $recordid, '');
						}
					}

				}
				$tmplmsg = unserialize($activity['tmplmsg']);
				$remark  = empty($tmplmsg['joinremark'])?$activity['title']:$tmplmsg['joinremark'];
				fx_message ('恭喜，你已报名成功', app_url('records/records/list'), 'success', $remark);
			}
		}
	}
}

if($_W['isajax'] && $op =='validquota'){//验证名额填写时的剩余名额；
	if ($quota > 0){
		if($joinnum >= $quota) {
			die(json_encode(array('errno'=>1,'message'=>"很遗憾！名额已经满了")));
		}elseif($joinnum + $teamnum > $quota){
			die(json_encode(array('errno'=>1,'message'=>"当前活动仅剩 " . ($quota - $joinnum) . ' 个名额')));
		}
	}
	die(json_encode(array('errno'=>0)));
}